﻿using com.uplus.common;
using com.uplus.log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using WebApi.Bill.Biz;
using WebApi.Models;

namespace WebApi.Common
{
    public class EmailUtil
    {
        #region 新版发送邮件util zt
        /// <summary>
        /// 发送邮件
        /// 管理员：    <$sOperator>
        /// 预定时间：  <$tOperate$>
        /// 预定人：    <$CreateUserName$>
        /// 楼层地点：	<$storey$>
        /// 工位名称：  <$Name$>
        /// 工位时间：	<$Date$>
        /// 工位状态：	<$Status$>
        /// 工位内容：	<$Content$>
        /// <$updateTime$>
        ///  //new EmailSender(emailModel.SEmailHost, "bayeyang@uplussoft.com", emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        /// //new EmailSender("smtp.qq.com", "304218152@qq.com", "82798611@qq.com", station.SName + "预定通知", "dfadfsadsf", "82798611@qq.com", "kwcxhrbteczjbgfd", "25", false, false).Send();
        /// </summary>
        //public static void SendStationEmail(BookStationModel bookStation, string template, List<LoginModel> userList, StationModel stationModel)
        //{
        //    NameValueCollection replaceCol = new NameValueCollection();
        //    LoginModel bookUser = null;
        //    StationModel station = null;
        //    DepartmentModel dep = null;
        //    EmailTemplateModel emailTemp = null;
        //    string tStartDate = "";
        //    string tEndDate = "";
        //    bool isLongTerm = false;
        //    //工位预定处预定
        //    if (null != bookStation && !string.IsNullOrEmpty(bookStation.Code))
        //    {
        //        tStartDate = bookStation.TStartDate.ToString();
        //        tEndDate = bookStation.TEndDate.ToString();
        //        station = BizBase.Get<BizStation>().Get(bookStation.FkStation);
        //        bookUser = BizBase.Get<BizLogin>().GetModel(bookStation.FkLogin);
        //        dep = BizBase.Get<BizDepartment>().Get(bookUser.FkDepartment);
        //        replaceCol.Add("sOperator", bookStation?.SOperator);
        //        replaceCol.Add("tOperate", bookStation?.TOperate.ToString());
        //    }
        //    //工位维护处绑定
        //    if (null != stationModel && !string.IsNullOrEmpty(stationModel.Code))
        //    {
        //        station = stationModel;
        //        if (station.IsLongTerm == 1)
        //            isLongTerm = true;
        //        else
        //        {
        //            tStartDate = station.TStartDate.ToString();
        //            tEndDate = station.TEndDate.ToString();
        //        }
        //        bookUser = BizBase.Get<BizLogin>().GetModel(station.SUserId);
        //        dep = BizBase.Get<BizDepartment>().Get(station.FkDepartment);
        //        replaceCol.Add("sOperator", station?.SOperator);
        //        replaceCol.Add("tOperate", station?.TOperate.ToString());
        //    }
        //    userList.Add(bookUser);
        //    StoreyAreaModel storey = BizBase.Get<BizStoreyArea>().Get(station?.FkStorey);
        //    List<EmailModel> emailModels = BizBase.Get<BizEmail>().GetList();
        //    EmailModel emailModel = new EmailModel();
        //    string mailBody = "";
        //    string toMail = "";
        //    userList?.ForEach(x =>
        //    {
        //        if (!string.IsNullOrEmpty(x?.SEmail))
        //        {
        //            if(!toMail.Contains(x.SEmail))
        //                toMail += x.SEmail + ",";
        //        }
        //    });
        //    if (!string.IsNullOrEmpty(toMail))
        //    {
        //        toMail = toMail.Trim(',');
        //    }
            
        //    replaceCol.Add("CreateUserName", bookUser?.SName + "(" + dep?.SName + ")");
        //    replaceCol.Add("storey", storey?.SName);//楼层
        //    replaceCol.Add("Name", station?.SName);//工位名称
        //    if (isLongTerm)
        //        replaceCol.Add("Date", "长期");
        //    else
        //        replaceCol.Add("Date", tStartDate + " ~ " + tEndDate);
        //    replaceCol.Add("Content", bookStation?.SRemark);
        //    //replaceCol.Add("tOperate", bookStation?.TOperate.ToString());
        //    replaceCol.Add("updateTime", DateTime.Now.ToString());
        //    if (null != bookStation)
        //    {
        //        if (bookStation?.NAudit == 2)
        //        {
        //            replaceCol.Add("Status", "已审核");
        //        }

        //        else if (bookStation?.NAudit == 3)
        //        {
        //            replaceCol.Add("Status", "未通过");
        //        }
        //        else if (bookStation?.NStatus == 6)
        //        {
        //            replaceCol.Add("Status", "已取消");
        //        }
        //        else if (bookStation?.NStatus == 7)
        //        {
        //            replaceCol.Add("Status", "管理员取消");
        //        }
        //        else
        //        {
        //            replaceCol.Add("Status", "待审核");
        //        }
        //    }
        //    if (null != emailModels && emailModels.Count > 0)
        //    {
        //        emailModel = emailModels[0];
        //    }
        //    Log4Helper.Debug("", "email地址toMail： " + toMail, null);

        //    emailTemp = BizBase.Get<BizEmailTemplate>().GetList(template)?.First<EmailTemplateModel>();
        //    if(null != emailTemp)
        //    {
        //        mailBody = BulidByFile(emailTemp?.SEmailContent, replaceCol); //2524643801@qq.com
        //        //new EmailSender(emailModel.SEmailHost, "13671727486@163.com,dory_zheng@163.com,2524643801@qq.com", emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //        new EmailSender(emailModel.SEmailHost, toMail, emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //    }
        //}
        #endregion

        #region 工位发送邮件util zt
        /// <summary>
        /// 发送邮件
        /// 预定人：    <$CreateUserName$>
        /// 楼层地点：	<$storey$>
        /// 工位名称：  <$Name$>
        /// 工位时间：	<$Date$>
        /// 工位状态：	<$Status$>
        /// 工位内容：	<$Content$>
        /// <$updateTime$>
        /// </summary>
        //public static void SendStationEmail1(BookStationModel bookStation, string template, List<LoginModel> userList, StationModel stationModel)
        //{
        //    LoginModel bookUser = null ;
        //    StationModel station = null;
        //    DepartmentModel dep = null;
        //    EmailTemplateModel emailTemp = null;
        //    string tStartDate = "";
        //    string tEndDate = "";
        //    bool isLongTerm = false;
        //    //工位预定处预定
        //    if (null != bookStation && !string.IsNullOrEmpty(bookStation.Code))
        //    {
        //        tStartDate = bookStation.TStartDate.ToString();
        //        tEndDate = bookStation.TEndDate.ToString();
        //        station = BizBase.Get<BizStation>().Get(bookStation.FkStation);
        //        bookUser = BizBase.Get<BizLogin>().GetModel(bookStation.FkLogin);
        //        dep = BizBase.Get<BizDepartment>().Get(bookUser.FkDepartment);
        //    }
        //    //工位维护处绑定
        //    if (null != stationModel && !string.IsNullOrEmpty(stationModel.Code))
        //    {
        //        station = stationModel;
        //        if (station.IsLongTerm == 1)
        //            isLongTerm = true;
        //        else
        //        {
        //            tStartDate = station.TStartDate.ToString();
        //            tEndDate = station.TEndDate.ToString();
        //        }
        //        bookUser = BizBase.Get<BizLogin>().GetModel(station.SUserId);
        //        dep = BizBase.Get<BizDepartment>().Get(station.FkDepartment);
        //    }
        //    userList.Add(bookUser);
            

        //    StoreyAreaModel storey = BizBase.Get<BizStoreyArea>().Get(station?.FkStorey); 

        //    List<EmailModel> emailModels = BizBase.Get<BizEmail>().GetList();
        //    EmailModel emailModel = new EmailModel();
        //    string mailBody = "";
        //    string toMail = "";
        //    userList?.ForEach(x =>
        //    {
        //        if (!string.IsNullOrEmpty(x?.SEmail))
        //        {
        //            toMail += x.SEmail + ",";
        //        }
                
        //    });
        //    if (!string.IsNullOrEmpty(toMail))
        //    {
        //        toMail = toMail.Trim(',');
        //    }
        //    NameValueCollection replaceCol = new NameValueCollection();
        //    replaceCol.Add("CreateUserName", bookUser?.SName+"("+dep?.SName+")");
        //    replaceCol.Add("storey", storey?.SName);//楼层
        //    replaceCol.Add("Name", station?.SName);//工位名称
        //    if(isLongTerm)
        //        replaceCol.Add("Date", "长期");
        //    else
        //        replaceCol.Add("Date", tStartDate + " ~ " + tEndDate);
        //    replaceCol.Add("Content", bookStation?.SRemark);
        //    replaceCol.Add("updateTime", DateTime.Now.ToString());
        //    if(null != bookStation)
        //    {
        //        if (bookStation?.NAudit == 2)
        //        {
        //            replaceCol.Add("Status", "已审核");
        //        }

        //        else if (bookStation?.NAudit == 3)
        //        {
        //            replaceCol.Add("Status", "未通过");
        //        }
        //        else if (bookStation?.NStatus == 6)
        //        {
        //            replaceCol.Add("Status", "已取消");
        //        }
        //        else if (bookStation?.NStatus == 7)
        //        {
        //            replaceCol.Add("Status", "管理员取消");
        //        }
        //        else
        //        {
        //            replaceCol.Add("Status", "待审核");
        //        }
        //    }
            
        //    if (null != emailModels && emailModels.Count > 0)
        //    {
        //        emailModel = emailModels[0];
        //    }
        //    Log4Helper.Debug("", "email地址toMail： " + toMail, new Exception());
        //    switch (template)
        //    {
        //        case "NewMeeting":
        //            //<$CreateUserName$> 于 <$Date$> 预定的 <$Name$> 已经预定成功.
        //            emailTemp = BizBase.Get<BizEmailTemplate>().GetList("NewMeeting")?.First<EmailTemplateModel>();
        //            mailBody = BulidByFile(emailTemp?.SEmailContent, replaceCol);
        //            //new EmailSender(emailModel.SEmailHost, "bayeyang@uplussoft.com", emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //            new EmailSender(emailModel.SEmailHost, toMail, emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //            //new EmailSender("smtp.qq.com", "304218152@qq.com", "82798611@qq.com", station.SName + "预定通知", "dfadfsadsf", "82798611@qq.com", "kwcxhrbteczjbgfd", "25", false, false).Send();

        //            break;
        //        case "UpdateMeeting":
        //            //<$Name$>, 被 <$CreateUserName$> 修改
        //            emailTemp = BizBase.Get<BizEmailTemplate>().GetList("UpdateMeeting")?.First<EmailTemplateModel>();
        //            mailBody = BulidByFile(emailTemp?.SEmailContent, replaceCol);
        //            new EmailSender(emailModel.SEmailHost, toMail, emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //            break;
        //        case "CancelMeeting":
        //            //<$Date$> 预定的 <$Name$>, <$updateTime$>被<$CreateUserName$>取消
        //            if (bookStation?.NStatus == 7)
        //            {
        //                emailTemp = BizBase.Get<BizEmailTemplate>().GetList("CancelAdminMeeting")?.First<EmailTemplateModel>();
        //                mailBody = BulidByFile(emailTemp?.SEmailContent, replaceCol);
        //                new EmailSender(emailModel.SEmailHost, toMail, emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //            }
        //            else
        //            {
        //                emailTemp = BizBase.Get<BizEmailTemplate>().GetList("CancelAdminMeeting")?.First<EmailTemplateModel>();
        //                mailBody = BulidByFile(emailTemp?.SEmailContent, replaceCol);
        //                new EmailSender(emailModel.SEmailHost, toMail, emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //            }
                   
        //            break;
        //        case "BeforeMeetingStart":
        //            //<$CreateUserName$> 预定的 <$Name$> 即将开始
        //            emailTemp = BizBase.Get<BizEmailTemplate>().GetList("BeforeMeetingStart")?.First<EmailTemplateModel>();
        //            mailBody = BulidByFile(emailTemp?.SEmailContent, replaceCol);
        //            new EmailSender(emailModel.SEmailHost, toMail, emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //            break;
        //        case "BeforeMeetingFinish":
        //            //<$Name$> 即将结束
        //            emailTemp = BizBase.Get<BizEmailTemplate>().GetList("BeforeMeetingFinish")?.First<EmailTemplateModel>();
        //            mailBody = BulidByFile(emailTemp?.SEmailContent, replaceCol);
        //            new EmailSender(emailModel.SEmailHost, toMail, emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //            break;
        //        case "AuditMeeting":
        //            //<$Date$> 预定的 <$Name$> 已通过审核
        //            emailTemp = BizBase.Get<BizEmailTemplate>().GetList("AuditMeeting")?.First<EmailTemplateModel>();
        //            mailBody = BulidByFile(emailTemp?.SEmailContent, replaceCol);
        //            new EmailSender(emailModel.SEmailHost, toMail, emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //            break;
        //        case "AuditNotPassMeeting":
        //            //<$Date$> 预定的 <$Name$>, 审核未通过
        //            emailTemp = BizBase.Get<BizEmailTemplate>().GetList("AuditNotPassMeeting")?.First<EmailTemplateModel>();
        //            mailBody = BulidByFile(emailTemp?.SEmailContent, replaceCol);
        //            new EmailSender(emailModel.SEmailHost, toMail, emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //            break;
        //        case "AdminAuditMeeting"://管理员需要审核会议模版
        //            emailTemp = BizBase.Get<BizEmailTemplate>().GetList("AdminAuditMeeting")?.First<EmailTemplateModel>();
        //            mailBody = BulidByFile(emailTemp?.SEmailContent, replaceCol);
        //            new EmailSender(emailModel.SEmailHost, toMail, emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //            break;
        //        case "SignCodeMeeting":
        //            //无
        //            emailTemp = BizBase.Get<BizEmailTemplate>().GetList("SignCodeMeeting")?.First<EmailTemplateModel>();
        //            mailBody = BulidByFile(emailTemp?.SEmailContent, replaceCol);
        //            new EmailSender(emailModel.SEmailHost, toMail, emailModel.SEmailName, emailTemp?.STemplateName, mailBody, emailModel.SEmailName, emailModel.SEmailPwd, emailModel.SEmailPort, false, false).Send();
        //            break;

        //    }
        //}

        #endregion

        #region 解析模板数据 zt
        /// <summary>
        /// 获取mailBody 
        /// </summary>
        /// <param name="template">templateContent</param>
        /// <param name="values">NameValueCollection</param>
        /// <returns>string</returns>
        public static string BulidByFile(string template, NameValueCollection values)
        {
            return BulidByFile(template, values, "<$", "$>");
        }

        /// <summary>
        /// 获取mailBody 
        /// </summary>
        /// <param name="template"></param>
        /// <param name="values">NameValueCollection obj</param>
        /// <param name="prefix"></param>
        /// <param name="postfix"></param>
        /// <returns></returns>
        public static string Build(string template, NameValueCollection values, string prefix, string postfix)
        {
            if (values != null)
            {
                foreach (DictionaryEntry entry in values)
                {
                    template = template.Replace(string.Format("{0}{1}{2}", prefix, entry.Key, postfix), entry.Value.ToString());
                }
            }
            return template;
        }


        /// <summary>
        /// 获取mailBody 
        /// </summary>
        /// <param name="templateContent"></param>
        /// <param name="values"></param>
        /// <param name="prefix"></param>
        /// <param name="postfix"></param>
        /// <returns></returns>
        public static string BulidByFile(string templateContent, NameValueCollection values, string prefix, string postfix)
        {
            string template = string.Empty;
            try
            {
                template = templateContent;
                if (values != null)
                {
                    foreach (string key in values.AllKeys)
                    {
                        template = template.Replace(string.Format("{0}{1}{2}", prefix, key, postfix), values[key]);
                        //Log4Helper.Info("", "values[{key}]: " + values[key]);
                    }
                }
                //Log4Helper.Info("", "email获取string: " + template);
            }
            catch (Exception ex)
            {
                Log4Helper.Error("", "获取mailBody！", ex);
            }
            return template;
        }
        #endregion
    }
}
